<template>
  <div>

    <el-tabs v-model="editableTabsValue" type="card"  @tab-click="handleClick" @tab-remove="removeTab">
      <el-tab-pane v-for="(item) in editableTabs" :key="item.name" :label="item.title" :name="item.name"
        :closable="item.name!=='1'"
      >
        <router-view name="menuUrl"></router-view>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import StorageEventBus from '@/util/StorageEventBus.js';
  import {
    setEditableTabs,
    getEditableTabs,
    EDITABLE_TABS,
    getEditableTabsValue,
    setMenuSelectedIndex
  } from '@/util/storage.js'
  export default {
    data() {
      return {
        editableTabsValue: '', //记录当前所选中的是第几个tab
        editableTabs: [],
        tabIndex: 1
      }
    },
    mounted() {
      this.editableTabs = getEditableTabs()
      this.editableTabsValue = getEditableTabsValue()
      // 监听存储事件
      StorageEventBus.$on('storageChanged', this.handleStorageChange);
    },
    methods: {
      handleStorageChange() {
        this.editableTabs = getEditableTabs()
        this.editableTabsValue = getEditableTabsValue()
      },
      handleClick(targetName) {
        //console.log("targetName",targetName.label)
        let tabs = this.editableTabs;
        let index = this.editableTabsValue;
        this.$router.push(tabs[parseInt(index) - 1].url)

        setMenuSelectedIndex(targetName.label)
        StorageEventBus.$emit('storageChangedMenu');
      },
      removeTab(targetName) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      }
    }
  }
</script>
<style scoped>
  .el-tabs {
    height: 810px;
  }
</style>
